//////////////////////////////////////////////////////////////////////////
// FileName:EMPForm.aspx
// CreateBy:Fenky
// CreateDate:2009-8-4
// Description:
//		Emp Form List and Add Page
//      
// Modify Log:20100301:Use Date Server Control to replace the UserControl --DragonXiong
//	
// Copyright:
/////////////////////////////////////////////////////////////////////////
using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Auto.Data.HumanResource;
using Auto.Web.Common;
using Auto.Components;
using Auto.Data.Security;


namespace BaseSystem._System
{
    public partial class EMPForm : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.UcDivEmp1.EmpID += new BaseSystem._System.UserControl.ucDivEmp.EmpIDClickEventHandler(UcDivEmp1_EmpID);
            if (!IsPostBack)
            {
                InitPage();
            }
        }

        private void InitPage()
        {
            this.txtRoles.Attributes.Add("onfocus", "this.blur()");
            this.txtAccessInfo.Attributes.Add("onfocus", "this.blur()");
            //this.chkCopyToUser.Attributes.Add("onclick", "TableRowDisplay(this.checked)");
            this.ddlAccess.Attributes.Add("onchange", String.Format("document.getElementById('{0}').value = '';SetAccessInfo(this.options[this.selectedIndex].value)", this.txtAccessInfo.ClientID));
            this.UcDivEmp1.TreeInit();
        }

        #region EmpBasic Info
        void UcDivEmp1_EmpID(string empID)
        {
            ClearText();
            this.chkCopyToUser.Checked = true;
            this.btnAdd.Visible = false;
            this.btnUpdate.Visible = true;
            this.txtEmpID.ReadOnly = true;
            EmpBasic emp = new EmpBasic(empID);
            if (emp != null)
            {
                this.txtCardNO.Text = emp.CardNO;
                this.txtEmail.Text = emp.Email;
                this.txtEmpDivs.Text = string.Empty;
                foreach (EmpDivisions empDivs in emp.ListEmpDivisions)
                {
                    this.txtEmpDivs.Text += empDivs.DivID + ",";
                }

                this.txtEmpDivs.Text = this.txtEmpDivs.Text.TrimEnd(',');

                tr0.Attributes["style"] = string.Format("display: {0};", !string.IsNullOrEmpty(txtEmpDivs.Text) ? "block" : "none");
              
                //
                this.txtEmpID.Text = emp.EmpID;
                this.txtLevelNO.Text = emp.LevelNO;
                this.txtName.Text = emp.Name;
                this.txtNote.Text = emp.Note;
                this.txtOfficePhoneExt.Text = emp.OfficePhoneExt;
                this.txtPersonID.Text = emp.PersonID;
                this.UcDateTextBox1.CalendarDateText = emp.BirthDay;
                this.UcDDLDivision1.DivID = emp.DivID;
                SetRoles(emp.EmpID);
                SetAccessInfo(emp.EmpID);
            }
        }

        private EmpBasic GetEmpBasic()
        {
            this.chkCopyToUser.Checked = true;

            EmpBasic emp = new EmpBasic(txtEmpID.Text);
            emp.PersonID = txtPersonID.Text;
            emp.ActionEmpID = SessionBox.User.EmpID;
            emp.BirthDay = UcDateTextBox1.CalendarDate.ToString();
            emp.CardNO = txtCardNO.Text;
            emp.DivID = this.UcDDLDivision1.DivID;
            emp.Email = txtEmail.Text;
            emp.EmpID = txtEmpID.Text;
            emp.LastUpdateDate = DateTime.Now;
            emp.LastUpdateIP = Request.ServerVariables["Remote_Addr"];
            emp.LevelNO = txtLevelNO.Text;
            emp.Married = Convert.ToBoolean(ddlMarried.SelectedValue);
            emp.Name = txtName.Text;
            emp.Note = txtNote.Text;
            emp.OfficePhoneExt = txtOfficePhoneExt.Text;
            emp.sex = Convert.ToBoolean(ddlSex.SelectedValue);

            emp.ListEmpDivisions = new List<EmpDivisions>();


            EmpDivisions empDivs = new EmpDivisions();
            empDivs.DivID = this.UcDDLDivision1.DivID;
            empDivs.EmpID = this.txtEmpID.Text;
            empDivs.Main = true;
            emp.ListEmpDivisions.Add(empDivs);

            string mainDivID = empDivs.DivID;

            if (this.txtEmpDivs.Text != string.Empty)
            {
                string[] empDivValues = this.txtEmpDivs.Text.Split(',');
                foreach (string empDivValue in empDivValues)
                {
                    if (empDivValue == mainDivID)
                    {
                        continue;
                    }
                    empDivs = new EmpDivisions();
                    empDivs.DivID = empDivValue;
                    empDivs.EmpID = this.txtEmpID.Text;
                    empDivs.Main = false;
                    emp.ListEmpDivisions.Add(empDivs);
                }
            }
            if (chkCopyToUser.Checked)
            {
                emp.Users = GetUsers();
            }

            return emp;
        }
        #endregion EmpBasic Info

        private void ClearText()
        {
            this.txtAccessInfo.Text = string.Empty;
            this.txtCardNO.Text = string.Empty;
            this.txtEmail.Text = string.Empty;
            this.txtEmpDivs.Text = string.Empty;
            this.txtEmpDivs.Text = string.Empty;
            this.txtEmpID.Text = string.Empty;
            this.txtLevelNO.Text = string.Empty;
            this.txtName.Text = string.Empty;
            this.txtNote.Text = string.Empty;
            this.txtOfficePhoneExt.Text = string.Empty;
            this.txtPersonID.Text = string.Empty;
            this.UcDateTextBox1.CalendarDateText = string.Empty;
            hfRole.Value = string.Empty;
            this.txtRoles.Text = string.Empty;
        }

        #region Set User Info
        private void SetAccessInfo(string empID)
        {
            this.ddlAccess.ClearSelection();
            Users user = new Users(empID);
            if (user.UserAccessDivision != null && user.UserAccessDivision.ListUserAccessDivison != null && user.UserAccessDivision.ListUserAccessDivison.Count > 0)
            {
                this.ddlAccess.SelectedIndex = 2;
                foreach (UserAccessDivison div in user.UserAccessDivision.ListUserAccessDivison)
                {
                    this.txtAccessInfo.Text += div.DivID + ",";
                }
            }
            else if (user.UserAccessEmp != null && user.UserAccessEmp.ListUserAccessEmp != null && user.UserAccessEmp.ListUserAccessEmp.Count > 0)
            {
                this.ddlAccess.SelectedIndex = 1;
                foreach (UserAccessEmp emp in user.UserAccessEmp.ListUserAccessEmp)
                {
                    this.txtAccessInfo.Text += emp.EmpID + ",";
                }
            }
            switch (this.ddlAccess.SelectedIndex)
            {
                case 1: btnGetAccessInfo.InnerHtml = Resources.Base.EmpInfo; break;
                case 2: btnGetAccessInfo.InnerHtml = Resources.Base.DivInfo; break;
            }
            this.txtAccessInfo.Text = this.txtAccessInfo.Text.Trim(',');

            tr3.Attributes["style"] = string.Format("display: {0};", !string.IsNullOrEmpty(txtAccessInfo.Text) ? "block" : "none");
        }
        private void SetRoles(string empID)
        {
            Users user = new Users(empID);
            if (user.Roles != null && user.Roles.Items != null)
            {
                foreach (UsersRoles userRole in user.Roles.Items)
                {
                    this.txtRoles.Text += "[" + userRole.SysID + "," + userRole.RoleID + "," + (userRole.WithGrant? Resources.Base.AllowWithGrant : Resources.Base.ForbidWithGrant) + "]\n";
                    hfRole.Value += string.Empty + userRole.SysID + "," + userRole.RoleID + "," + userRole.WithGrant
                         + "|";
                }
                hfRole.Value = hfRole.Value.TrimEnd('|');
            }
        }
        #endregion Set User Info

        private string GetDiv(string input)
        {
            string result = input;
            string[] values = input.Split('|');
            if (values.Length > 0)
            {
                result = values[0];
            }
            return result;
        }



        #region Get User Info

        /// <summary>
        /// Gets the users.
        /// </summary>
        /// <returns></returns>
        private Users GetUsers()
        {
            Users result = null;
            result = new Users();
            result.UserID = this.txtEmpID.Text;
                result.CreateBy = SessionBox.User.UserID;
                result.DivID = this.UcDDLDivision1.DivID;
                result.EmpID = this.txtEmpID.Text;
                result.IsTopSuper = false;

                result.Roles = new UsersRoles(this.txtEmpID.Text);

                if (!string.IsNullOrEmpty(hfRole.Value))
                {
                    result.Roles.Items = GetUserRoles();
                }

                result.UserAccessDivision = new UserAccessDivison();
                result.UserAccessDivision.UserID = this.txtEmpID.Text;
                result.UserAccessEmp = new UserAccessEmp();
                result.UserAccessEmp.UserID = this.txtEmpID.Text;
                if (!string.IsNullOrEmpty(this.txtAccessInfo.Text))
                {
                    switch (this.ddlAccess.SelectedValue)
                    {
                        case "2": result.UserAccessDivision.ListUserAccessDivison = GetUserAccessDivison(); break;
                        case "1": result.UserAccessEmp.ListUserAccessEmp = GetUserAccessEmp(); break;
                    }
                }
         
            return result;
        }

        /// <summary>
        /// Gets the user roles.
        /// </summary>
        /// <returns></returns>
        private IList<UsersRoles> GetUserRoles()
        {
            
            string[] userRolesArray = hfRole.Value.Split('|');
            IList<UsersRoles> userRolesList = new List<UsersRoles>();

            foreach (string currentRole in userRolesArray)
            {
                string[] currentRoleArray = currentRole.Split(',');
                UsersRoles userRoles = new UsersRoles(this.txtEmpID.Text, currentRoleArray[0], currentRoleArray[1]);

                userRoles.WithGrant = Convert.ToBoolean(currentRoleArray[2]);
                userRolesList.Add(userRoles);
            }
            return userRolesList;
        }

        /// <summary>
        /// Gets the user access divison list
        /// </summary>
        /// <returns></returns>
        private IList<UserAccessDivison> GetUserAccessDivison()
        {
            string[] userAccessDivisonArray = txtAccessInfo.Text.Split(',');
            IList<UserAccessDivison> result = new List<UserAccessDivison>();

            foreach (string currentDiv in userAccessDivisonArray)
            {
                UserAccessDivison userAccessDivison = new UserAccessDivison(this.txtEmpID.Text, currentDiv);
                result.Add(userAccessDivison);
            }
            return result;
        }

        /// <summary>
        /// Gets the user access divison list
        /// </summary>
        /// <returns></returns>
        private IList<UserAccessEmp> GetUserAccessEmp()
        {
            string[] UserAccessEmpArray = txtAccessInfo.Text.Split(',');
            IList<UserAccessEmp> result = new List<UserAccessEmp>();

            foreach (string currentUserID in UserAccessEmpArray)
            {
                UserAccessEmp UserAccessEmp = new UserAccessEmp(this.txtEmpID.Text, currentUserID);
                result.Add(UserAccessEmp);
            }
            return result;
        }
        #endregion Get User Info

        #region Event

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            EmpBasic emp = GetEmpBasic();
            if (emp.IsNew)
            {
                try
                {
                    emp.Insert();
                }
                catch (Exception ex)
                {
                    Jscript.AjaxAlert(this, ex.Message);
                }
            }
        }
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            EmpBasic emp = GetEmpBasic(); 
            try
            {
                emp.Update();
            }
            catch (Exception ex)
            {
                Jscript.AjaxAlert(this, ex.Message);
            }
        }
        #endregion Event
    }
}
